package com.supor.aiot.common.utils

import android.app.Activity
import android.os.Build
import android.view.View.NO_ID
import android.view.ViewGroup
import com.android.baseconfig.common.utils.OnNavigationStateListener


/**
 *
 * @author: zook
 * @date: 2022/3/2
 */
class NavigationBarUtils {
    companion object {
        @JvmStatic
        fun isNavigationBarExist(activity: Activity?, onNavigationStateListener: OnNavigationStateListener) {
            activity?.run {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
                    activity.window.decorView.setOnApplyWindowInsetsListener { _, insets ->
                        var height: Int = getNavigationHeight(activity)
                        var isShowing = false
                        var b = 0
                        if (insets != null) {
                            b = insets.getSystemWindowInsetBottom()
                            isShowing = b == getNavigationHeight(activity)
                        }
                        if (b <= height) {
                            onNavigationStateListener.onNavigationState(isShowing, b)
                        }

                        insets
                    }
                }
            }
        }

        @JvmStatic
        fun isNavigationBarExist(activity: Activity): Boolean {
            val vp = activity.window.decorView as ViewGroup
            for (i in 0 until vp.childCount) {
                vp.getChildAt(i).context.packageName
                if (vp.getChildAt(i).id != NO_ID && "navigationBarBackground".equals(activity.resources.getResourceEntryName(vp.getChildAt(i).id))) {
                    return true
                }
            }
            return false
        }

        @JvmStatic
        fun getNavigationHeight(activity: Activity?): Int {
            if (null != activity) {
                activity.resources?.getIdentifier("navigation_bar_height",
                        "dimen", "android")?.run {
                    return if (this > 0) activity.resources.getDimensionPixelSize(this) else 0
                }
            }
            return 0;
        }
    }
}